package orm

import (
	"database/sql/driver"
	"fmt"
	"inventory/pkg/ecode"
	"strconv"
	"strings"
)

// IntArray integer[]
type IntArray []int

// Scan  implement sql.Scanner interface，Scan convert value to []int.
func (i *IntArray) Scan(value interface{}) error {
	arrayString, ok := value.(string)
	if !ok {
		return ecode.BadRequest(fmt.Sprint("Failed to convert string value:", value))
	}
	if len(arrayString) > 2 {
		ss := strings.Split(arrayString[1:len(arrayString)-1], ",")
		t := make([]int, len(ss))
		for i, s := range ss {
			e, _ := strconv.Atoi(s)
			t[i] = e
		}
		*i = t
	} else {
		*i = make([]int, 0)
	}
	return nil
}

// Value implement driver.Valuer interface，return string value.
func (i IntArray) Value() (driver.Value, error) {
	return "{" + strings.Trim(strings.Replace(fmt.Sprint(i), " ", ",", -1), "[]") + "}", nil
}

// StringArray integer[]
type StringArray []string

// Scan  implement sql.Scanner interface，Scan convert value to []int.
func (i *StringArray) Scan(value interface{}) error {
	arrayString, ok := value.(string)
	if !ok {
		return ecode.BadRequest(fmt.Sprint("Failed to convert string value:", value))
	}
	if len(arrayString) > 2 {
		ss := strings.Split(arrayString[1:len(arrayString)-1], ",")
		t := make([]string, len(ss))
		for i, s := range ss {
			t[i] = s
		}
		*i = t
	} else {
		*i = make([]string, 0)
	}
	return nil
}

// Value implement driver.Valuer interface，return string value.
func (i StringArray) Value() (driver.Value, error) {
	return "{" + strings.Trim(strings.Replace(fmt.Sprint(i), " ", ",", -1), "[]") + "}", nil
}
